package com.lanxiao.cloud.modules.log.application.assembler;

import com.lanxiao.cloud.common.core.dto.ResultModel;
import com.lanxiao.cloud.common.core.dto.UserBaseDto;
import com.lanxiao.cloud.common.fill.FillAppointment;
import com.lanxiao.cloud.common.fill.FillHandle;
import com.lanxiao.cloud.common.fill.FillHandleFactory;
import com.lanxiao.cloud.common.fill.FillType;
import com.lanxiao.cloud.common.web.bus.event.LogEvent;
import com.lanxiao.cloud.modules.log.application.dto.LogDto;
import com.lanxiao.cloud.modules.log.domain.Log;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
import org.springframework.stereotype.Component;

/**
 * @author ：qiaoliang
 * @date ：2021-10-15
 */
@Component
public class LogAssembler {

  private final FillHandleFactory fillHandleFactory;

  public LogAssembler(FillHandleFactory fillHandleFactory) {
    this.fillHandleFactory = fillHandleFactory;
  }

  public Log toLog(LogEvent<String> logEvent){
    return LogConverter.INSTANCE.toLog(logEvent);
  }

  public ResultModel<LogDto> toLogDto(List<Log> list, int count) {
    final List<LogDto> logDtos = LogConverter.INSTANCE.toLogDto(list);
    fillHandleFactory.fill(logDtos, new FillHandle<>(FillType.USER_INFO, LogDto::setCreateUser, o->o.getCreateUser().getId()));
    return new ResultModel<>(logDtos, count);
  }

  @Mapper
  public interface LogConverter {
    LogConverter INSTANCE = Mappers.getMapper(LogConverter.class);

    @Mappings({
        @Mapping(source = "createBy", target = "createUser.id"),
    })
    LogDto toLogDto(Log log);
    List<LogDto> toLogDto(List<Log> log);

    @Mappings({
        @Mapping(source = "service", target = "topic.name"),
        @Mapping(source = "serviceId",target = "topic.id"),
        @Mapping(source = "serviceType",target = "topic.type"),
        @Mapping(source = "curredTime",target = "createTime"),
    })
    Log toLog(LogEvent<String> logEvent);
  }

}
